package es.udima.geo.geoserver.rest;

import java.util.Collection;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import es.udima.geo.geoserver.business.UserController;
import es.udima.geo.geoserver.entities.User;
import es.udima.geo.geoserver.entities.UserUpdateResult;
import es.udima.geo.geoserver.entities.UserUpdateResultError;
import es.udima.geo.geoserver.rest.entities.IResponseError;
import es.udima.geo.geoserver.rest.entities.UserUpdateResponse;
import es.udima.geo.geoserver.rest.entities.UsersRetrieveResponse;

@Path("/admin/users")
public class UserAdminService {

    public UserAdminService() {
    }

    /**
     * 
     * @param userId
     * @return
     */
    @GET
    @Path("/{userId}")
    @Produces(MediaType.APPLICATION_JSON)
    public User retrieveUserByUserId(@PathParam("userId") String userId) {
	UserController uc = new UserController();
	return uc.retrieveUserByUserId(userId);
    }

    /**
     * 
     * @return
     */
    @GET
    @Path("/all")
    @Produces(MediaType.APPLICATION_JSON)
    public UsersRetrieveResponse retrieveAllUsers() {
	UserController uc = new UserController();
	List<User> users = uc.retrieveAllUsers();
	UsersRetrieveResponse res = new UsersRetrieveResponse();
	res.setUsers(users);

	return res;
    }

    /**
     * 
     * @param req
     * @return
     */
    @POST
    @Path("/update")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public UserUpdateResponse updateUser(User user) {
	UserController uc = new UserController();
	UserUpdateResponse res = new UserUpdateResponse();

	UserUpdateResult ur = uc.updateUser(user);
	if (ur.isUpdateSuccessful()) {
	    res.setUser(ur.getUser());
	} else {
	    res.addResponseErrors(translateUserUpdateErrors(ur.getErrors()));
	}

	return res;
    }

    /*-----------------------------------------------------------------------------------------------*/

    /**
     * 
     * @param errors
     * @return
     */
    private Collection<IResponseError> translateUserUpdateErrors(Collection<UserUpdateResultError> errors) {
	return new RestServiceErrorHelper().translateUserUpdateErrors(errors);
    }
}
